<?php
declare (strict_types=1);

namespace app\course\model\coupon;

use app\common\helper\util\SnowFlake;
use app\common\model\BaseModel;
use app\user\model\user\TicketCoupon;
use think\helper\Str;
use think\model\concern\SoftDelete;
use think\model\relation\BelongsTo;

/**
 * 用户卡券模型
 */
class CouponUser extends BaseModel
{
    use SoftDelete;

    /**
     * 表名
     *
     * @var string
     */
    protected $name = 'coupon_user';

    /**
     * 设置自动写入时间
     *
     * @var boolean
     */
    protected $autoWriteTimestamp = true;
    protected $hidden = ['delete_time'];
    protected static $couponPrefix = [
        1 => 'YhQ', // 优惠券
        2 => 'DzK', // 打折卡
        3 => 'KcK', // 课程卡
    ];

    /**
     * 定义字段类型
     *
     * @var array
     */
    protected $type = [
        'id'          => 'integer',
        'delete_time' => 'integer',
        'create_time' => 'integer',
    ];

    public function coupon(): BelongsTo
    {
        return $this->belongsTo(Coupon::class, 'coupon_id');
    }

    /**
     * 新增数据事件
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-13
     *
     * @param    [type]                         $coupon [description]
     * @return void [type]                                 [description]
     */
    public static function onBeforeInsert($model)
    {
        // 卡号生成
        $model->code = self::$couponPrefix[$model->coupon_type] . app(SnowFlake::class)->nextId() . Str::random(8);
        unset($model->coupon_type);
    }

    /**
     * 机构下用户可用卡券
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-04-29
     */
    public function scopeMhmUserCanUse($query, $mhm_id)
    {
        $query->where('mhm_id', $mhm_id);
        $query->where('user_id', request()->mid);
        $query->where('status', 0);
    }

}
